<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>角色菜单</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
</head>
<body>
<div class="layui-form " lay-filter="myForm">
    <input type="hidden" name="id" id="id">
    <div style="width:100%; " style="float: left">
        <div style="display: inline-block; width: 90%; height: 300px; padding: 10px; border: 1px solid #ddd; overflow: auto;">
            <ul id="menu-tree" class="demo-tree-more"></ul>
        </div>
    </div>
    <div class="layui-row layui-col-space10" >
        <div class="layui-col-xs10">
        </div>
        <div class="layui-col-xs2">
            <button type="button" class="layui-btn layui-btn-sm" lay-demo="getChecked" >确定</button>
        </div>
    </div>
</div>
<script src="../../lib/layui/layui.js" charset="utf-8"></script>
<script src="../../js/provider/my-utils.js" charset="utf-8"></script>
<script>
    var treelist = [];
    var rolemenupermission=[];
    var rolemenulist;
    layui.use(['tree', 'layer','form','util'], function () {
        var layer = layui.layer,
            $ = layui.jquery,
            form = layui.form,
            util = layui.util,
            tree = layui.tree;
        //获取已经拥有的权限菜单

        var id;
        if($("#id").val()!=null||$("#id").val()!=''){
            id =$("#id").val();
        }
        $.ajax({
            url: "/channel/sys-role/rel",
            type: "POST",
            dataType:"json",
            headers:{'Authorization':'Bearer '+ JSON.parse(localStorage.getItem('userdetail')).token},
            data:{roleid:id},
            success: function(data) {
                var rm=data.rolemenu;
                var rp = data.rolepermission;
                console.log("rm",rm);
                if (rp.length > 0) {
                    for (var k in rp) {
                        rolemenupermission.push(rp[k].permissionId);
                    }
                }
                console.log("rolemenupermission",rolemenupermission);
            },
            error:function (data) {
                console.log("error",data);
            }

        });
        //获取选中菜单
        util.event('lay-demo', {
            getChecked: function(othis){
                var checkedData = tree.getChecked('demoId1'); //根据树id获取选中节点的数据
                layer.alert(JSON.stringify(checkedData), {shade:0});
                localStorage.setItem("checkedData",JSON.stringify(checkedData));
                var iframeIndex = parent.layer.getFrameIndex(window.name);
                parent.layer.close(iframeIndex);
            }
        });
        var datalist;//菜单
        var permissionData;//权限
        //获取菜单
        $.ajax({
            url: "/channel/sys-menu/menulist",
            type: 'POST',
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('userdetail')).token
            },
            success: function (data) {
                datalist = data;
                rolemenulist=data;
                for (var o in datalist) {
                    var TMP={};
                    TMP.id = datalist[o].id;
                    TMP.title = datalist[o].title;
                    TMP.resourceType = "menu";
                    TMP.pid = datalist[o].pid;
                    treelist.push(TMP);
                }
                //获取权限
                $.ajax({
                    url: "/channel/sys-permission/listALL",
                    type: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('userdetail')).token
                    },
                    success: function (data) {
                        permissionData = data.data;
                        for(var o in permissionData){
                            var tmp={};
                            tmp.id = permissionData[o].id;
                            tmp.title = permissionData[o].name;
                            tmp.resourceType = "permission";
                            tmp.pid = permissionData[o].pid;
                            treelist.push(tmp);
                        }
                        for(var key in  treelist){
                            treelist[key].spread=true;
                        }
                        //转换树形json
                        treelist = transData(treelist,"id","pid","children");

                       //建立一个树形菜单
                        tree.render({
                            elem: '#menu-tree' //指定元素
                            , data:treelist
                            ,id:'demoId1'
                            ,isJump: false //是否允许点击节点时弹出新窗口跳转
                            ,showLine: false//是否开启连接线
                            ,showCheckbox: true  //是否显示复选框
                            ,onlyIconControl:true
                            ,click: function(obj) {
                                var clickdata = obj.data;  //获取当前点击的节点数据
                                // layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(clickdata));
                            }
                        });
                        tree.setChecked('demoId1',rolemenupermission);


                    }, error: function (data) {
                    }
                });
            }, error: function (data) {
            }
        });


    });


    //递归方法
    function transData(json, idStr, pidStr, chindrenStr) {
        var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = json.length;
        for (; i < len; i++) {
            hash[json[i][id]] = json[i];
        }
        for (; j < len; j++) {
            var aVal = json[j], hashVP = hash[aVal[pid]];
            if (hashVP) {
                !hashVP[children] && (hashVP[children] = []);
                hashVP[children].push(aVal);
            } else {
                r.push(aVal);
            }
        }
        return r;
    }
</script>
</body>
</html>